<script setup>
import axios from "axios";
import 'vant/lib/index.css';
import {showFailToast, showSuccessToast} from "vant";
import {useRouter} from  'vue-router'
let router = useRouter();


const onClickLeft = () => history.back();

let admin = ref({
  "userName": "",
  "password": "",
  "nickName": "",
  "phonenumber": "",
  "sex": "男"
});

const onSubmit = (values) => {
  axios.post('http://127.0.0.1:9000/school/web/admin/reg', admin.value)
      .then(response => {
        if (response.data.code === 200) {
          // 注册成功
          showSuccessToast(response.data.message);
          // 跳转到登录页面
          router.push("/login");
        } else {
          // 注册失败
          showFailToast(response.data.message);
        }
      })
      .catch(error => {
        console.error('注册请求发生错误：', error);
        if (error.code === 'ERR_NETWORK') {
          showFailToast('无法连接到服务器，请检查网络连接或联系管理员。');
        } else {
          showFailToast('注册失败，请检查输入信息或联系管理员。');
        }
      });
};
</script>

<template>
  <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
  />
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="admin.userName"
          name="userName"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="admin.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="admin.nickName"
          name="nickName"
          label="真实姓名"
          placeholder="真实姓名"
          :rules="[{ required: true, message: '请填写真实姓名' }]"
      />
      <van-field
          v-model="admin.phonenumber"
          name="phonenumber"
          label="手机号"
          placeholder="手机号"
          :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <!--   性别   -->
      <van-field name="sex" label="性别">
        <template #input>
          <van-radio-group v-model="admin.sex" direction="horizontal">
            <van-radio name="男">男</van-radio>
            <van-radio name="女">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped>

</style>